<?php

namespace Blog\Model;

use Hx\Mvc\Model\Table;

class User extends Table {

    public function __construct() {
        $this->setTable('fxh_user');
    }

    public function authorize($user, $password, $expire, $app = 'web') {
        $user = $this->only(array(
            'where' => 'user = :user AND roleName = "admin"',
            'param' => array(
                'user' => $user
            )
        ), 'id,user,password,nickName,email,url,avatar,roleName');
        if (!$user) {
            return -1;
        }
        $password = md5($user->id . '-' . $password);
        if ($password != $user->password) {
            return -2;
        }
        $user->token = $this->createToken($user->id, $expire, $app);
        unset($user->password);
        return $user;
    }

    private function createToken($user, $expire, $app) {
        $expire = time() + $expire * 3600 * 24;
        $token = md5($expire . '-' . uniqid());
        $this->setTable('fxh_token');
        $data = array(
            'userId'     => $user,
            'token'      => $token,
            'createTime' => time(),
            'expireTime' => $expire,
            'app'        => strtoupper($app)
        );
        $this->insert($data);
        $this->setTable('fxh_user');
        return $token;
    }

    public function check($user, $token, $app = 'web') {
        $this->setTable('fxh_token');
        $data = $this->only(array(
            'where' => 'userId = :id AND token = :t',
            'param' => array(
                'id' => $user,
                't'  => $token
            )
        ), 'expireTime,app');
        $this->setTable('fxh_user');
        if (!$data) {
            return FALSE;
        }
        if (time() > $data->expireTime) {
            return FALSE;
        }
        if (strtoupper($app) !== $data->app) {
            return FALSE;
        }
        return TRUE;
    }

    public function getById($id) {
        return $this->only(array(
            'where' => 'id = :id AND status = "active"',
            'param' => array('id' => $id)
        ), 'id,user,nickName,avatar,url,roleName');
    }
}